//创建用户相关的小仓库

import { defineStore } from "pinia"
import { reqLogin, reqLogout, reqUserInfo } from "../../api/user"
import { loginForm, loginRespData, userInfoRespData } from "../../api/user/type"
import type { UserState } from "./types/type.ts"
// import type { UserState } from "./types/type.ts"
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "../../utils/token"
//引入路由
import { constRouter } from "../../router/routers"

const useUserStore = defineStore("User", {
  state: (): UserState => {
    return {
      // token: localStorage.getItem("Token"),
      token: GET_TOKEN(),
      menuRoutes: constRouter, //仓库生成菜单需要的路由数组
      username: "",
      avatar: "",
    }
  },
  actions: {
    //用户登录
    async userLogin(data: loginForm) {
      const result: loginRespData = await reqLogin(data)
      console.log(result)
      if (result.code == 200) {
        this.token = result.data as string
        //本地持久化存储
        // localStorage.setItem("Token", result.data.token as string)
        SET_TOKEN(result.data as string)
        return "ok"
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息
    async userInfo() {
      //存储到仓库当中
      const result: userInfoRespData = await reqUserInfo()
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        return "ok"
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录
    async userLogout() {
      const result: any = await reqLogout()
      if (result.code == 200) {
        this.token = ""
        this.username = ""
        this.avatar = ""
        REMOVE_TOKEN()
        return "ok"
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})
export default useUserStore
